﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MakeIT.MiraPark.Negocios;

namespace MiraPark
{
    public partial class FormCadastroModelo : Form
    {
        private string operacao = "";

        public FormCadastroModelo()
        {
            InitializeComponent();
        }

        private void FormCadastroModelo_Load(object sender, EventArgs e)
        {
            //Popular a lista de modelos cadastrados
            this.dataGridViewModelos.DataSource = ModelBO.getModelos();
            this.comboBoxMarca.DataSource = ModelBO.getMarcas();
            this.comboBoxTipo.DataSource = ModelBO.getTipoVeiculos();
            this.comboBoxPorte.DataSource = ModelBO.getPorteVeiculos();
            setupButtonsControls();
            setupTreeView();
        }

        private void dataGridViewModelo_SelectionChanged(object sender, EventArgs e)
        {
            setupButtonsControls();
        }

        private void buttonNovo_Click(object sender, EventArgs e)
        {
            this.operacao = "novo";
            this.numericUpDownOrdem.Value = 999;
            setupButtonsControls();
        }

        private void buttonCancelar_Click(object sender, EventArgs e)
        {
            this.operacao = "cancelar";
            setupButtonsControls();
        }

        private void buttonEditar_Click(object sender, EventArgs e)
        {
            this.operacao = "editar";
            setupButtonsControls();
        }

        private void buttonExcluir_Click(object sender, EventArgs e)
        {
            List<ModeloVO> modeloList = (List<ModeloVO>)this.dataGridViewModelos.DataSource;
            ModeloVO modelo = modeloList[this.dataGridViewModelos.CurrentRow.Index];

            if (!ModelBO.readyToDeleteModelo(modelo.idModelo))
            {
                MessageBox.Show(this, "Modelo não pode ser excluído pois já está associada a Veículos", "Aviso");
                return;
            }

            this.operacao = "excluir";

            DialogResult dr = MessageBox.Show(this, "Confirma a exclusão do modelo " + modelo.modelo, "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr.ToString().Equals("Yes"))
            {
                ModelBO.delModelo(modelo);

                int nRow = this.dataGridViewModelos.CurrentRow.Index;
                this.dataGridViewModelos.DataSource = ModelBO.getModelos();
                if (this.dataGridViewModelos.Rows.Count > 0)
                {
                    dataGridViewModelos.CurrentCell = dataGridViewModelos.Rows[Math.Min(nRow, this.dataGridViewModelos.Rows.Count - 1)].Cells[1];
                    dataGridViewModelos.Rows[Math.Min(nRow, this.dataGridViewModelos.Rows.Count - 1)].Selected = true;
                }

                setupButtonsControls();
                setupTreeView();
            }
        }

        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            String erros = "";
            if (this.textBoxModelo.Text.Trim().Length == 0)
                erros = erros + "Modelo deve ser informado.\r\n";
            if (this.comboBoxMarca.SelectedValue == null)
                erros = erros + "Marca deve ser informado.\r\n";
            if (this.comboBoxTipo.SelectedValue == null)
                erros = erros + "Tipo deve ser informado.\r\n";
            if (this.comboBoxPorte.SelectedValue == null)
                erros = erros + "Porte deve ser informado.\r\n";

            if (erros.Length > 0)
            {
                MessageBox.Show(this, erros, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ModeloVO modelo = null;

            if (this.operacao.Equals("novo"))
            {

                modelo = ModeloVO.CreateModeloVO();
                modelo.modelo = this.textBoxModelo.Text;
                modelo.obs = this.textBoxObs.Text;
                modelo.idMarca = (int)this.comboBoxMarca.SelectedValue;
                modelo.idTipoVeiculo = (int)this.comboBoxTipo.SelectedValue;
                modelo.idPorteVeiculo = (int)this.comboBoxPorte.SelectedValue;
                modelo.ordem = (int)this.numericUpDownOrdem.Value;

                modelo.idModelo = (int)ModelBO.newModelo(modelo);
            }
            if (this.operacao.Equals("editar"))
            {
                List<ModeloVO> modeloList = (List<ModeloVO>)this.dataGridViewModelos.DataSource;
                modelo = modeloList[this.dataGridViewModelos.CurrentRow.Index];

                modelo.modelo = this.textBoxModelo.Text;
                modelo.obs = this.textBoxObs.Text;
                modelo.idMarca = (int)comboBoxMarca.SelectedValue;
                modelo.idTipoVeiculo = (int)comboBoxTipo.SelectedValue;
                modelo.idPorteVeiculo = (int)comboBoxPorte.SelectedValue;
                modelo.ordem = (int)this.numericUpDownOrdem.Value;

                ModelBO.setModelo(modelo);
            }
            this.operacao = "salvar";

            List<ModeloVO> listModeloVOs = ModelBO.getModelos();
            dataGridViewModelos.DataSource = listModeloVOs;
            int nRow = listModeloVOs.FindIndex(a => a.idModelo == modelo.idModelo);
            dataGridViewModelos.CurrentCell = dataGridViewModelos.Rows[nRow].Cells[1];
            dataGridViewModelos.Rows[nRow].Selected = true;

            setupButtonsControls();
            setupTreeView();
        }


        private void setupTreeView()
        {
            treeView1.Nodes.Clear();
            
            int idMarcaAnt=-1;
            TreeNode node = null;
            foreach( ModeloVO modeloVO in ModelBO.getModelos(true,true))
            {
                if (idMarcaAnt!=modeloVO.idMarca){
                    node = treeView1.Nodes.Add(modeloVO.marcaVO.marca);
                    idMarcaAnt=modeloVO.idMarca;
                }
                node.Nodes.Add(modeloVO.modelo).Tag = modeloVO;
            }
        }

        private void setupButtonsControls()
        {
            bool haRows = this.dataGridViewModelos.Rows.Count > 0 && this.dataGridViewModelos.CurrentRow!=null;
            bool novo = this.operacao.Equals("novo");
            bool edit = this.operacao.Equals("editar");
            bool canc = this.operacao.Equals("cancelar");

            this.buttonCancelar.Enabled = novo || edit;
            this.buttonNovo.Enabled = !novo && !edit;
            this.buttonEditar.Enabled = haRows && !novo && !edit;
            this.buttonExcluir.Enabled = haRows && !novo && !edit;
            this.buttonSalvar.Enabled = novo || edit;

            this.textBoxModelo.Enabled = novo || edit;
            this.textBoxObs.Enabled = novo || edit;
            this.comboBoxMarca.Enabled = novo || edit;
            this.comboBoxTipo.Enabled = novo || edit;
            this.comboBoxPorte.Enabled = novo || edit;
            this.numericUpDownOrdem.Enabled = novo || edit;

            this.dataGridViewModelos.Enabled = !novo && !edit;

            if (!haRows || novo)
            {
                this.textBoxId.Text = "";
                this.textBoxModelo.Text = "";
                this.textBoxObs.Text = "";
                this.comboBoxMarca.SelectedIndex = 0;
                this.comboBoxPorte.SelectedIndex = 0;
                this.comboBoxTipo.SelectedIndex = 0;
                this.numericUpDownOrdem.Value = 999;
            }
            else {
                List<ModeloVO> modeloList = (List<ModeloVO>)this.dataGridViewModelos.DataSource;
                ModeloVO modelo = modeloList[this.dataGridViewModelos.CurrentRow.Index];
                this.textBoxId.Text = modelo.idModelo.ToString();
                this.textBoxModelo.Text = modelo.modelo;
                this.textBoxObs.Text = modelo.obs;
                this.comboBoxMarca.SelectedValue = modelo.idMarca;
                this.comboBoxTipo.SelectedValue = modelo.idTipoVeiculo;
                this.comboBoxPorte.SelectedValue = modelo.idPorteVeiculo;
                this.numericUpDownOrdem.Value = modelo.ordem;


            }
            if (novo || edit){
                this.textBoxModelo.Focus();
            }

        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Tag != null)
            {
                ModeloVO modeloVO = (ModeloVO)node.Tag;
                foreach (DataGridViewRow dgvRow in dataGridViewModelos.Rows)
                {
                    if (modeloVO.idModelo == (int)dgvRow.Cells["idModelo"].Value)
                    {
                        dgvRow.Selected = true;
                        dataGridViewModelos.CurrentCell = dgvRow.Cells["modelo"];
                        dataGridViewModelos.FirstDisplayedScrollingRowIndex = dgvRow.Index;
                        setupButtonsControls();
                        break;
                    }
                }
            }
        }

        private void buttonListagem_Click(object sender, EventArgs e)
        {
            FormReportModelo formx = new FormReportModelo();
            formx.MdiParent = this.MdiParent;
            formx.Show();
        }

     }
}
